package pc;

//lock 版

// 线程之前通信
// 生产者消费者
// 判断等待，执行业务，通知

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//A 和 B 之间通信
// A++ 完后 通知 B--
public class PC2 {

    public static void main(String[] args) {

        ZY zy = new ZY();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                try {
                    zy.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                try {
                    zy.unincr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                try {
                    zy.unincr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                try {
                    zy.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"D").start();
    }


   static class ZY{
        private int num = 0;

        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();


        public void incr() throws InterruptedException {

            lock.lock();
            try {
                while(num != 0){
                    //等待
                    condition.await();
                }
                num++;
                System.out.println(Thread.currentThread().getName()+":  num ++ 当前num值:"+num);
                //唤醒其他线程
                condition.signalAll();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }


        public  void unincr() throws InterruptedException {
            lock.lock();
            try {
                while(num == 0){
                    //等待
                    condition.await();
                }
                num--;
                System.out.println(Thread.currentThread().getName()+"   num -- 当前num值:"+num);
                condition.signalAll();
            }catch (Exception e){

                e.printStackTrace();
            }finally {
                lock.unlock();
            }

        }
    }
}
